package list;

import java.util.Arrays;

public class Mylist implements IList {
    public int[] elem;
    public int useSize;
    public static final int DEFALIT_LENGTH = 5;
    public Mylist() {
        elem = new int[ DEFALIT_LENGTH ];

    }
//打印顺序表所有的元素
    @Override
    public void display() {
        for (int i = 0; i < useSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
//默认添加到数组的最后位置
    @Override
    public void add(int data) {
//1.判断是否满了
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[useSize] = data;
        useSize++;
    }


    @Override
    public boolean isFull() {
        return useSize == elem.length;
    }

    @Override
    public void add(int pos, int data) {
        //1.pos位置的判断
        checkPosOfAdd(pos);
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        for (int i = useSize-1; i >= pos; i--) {
            elem[i+1] = elem[i];

        }
        elem[pos] = data;
        useSize++;
    }
//查找当前元素是否存在
    @Override
    public boolean contains(int tofind) {
        for (int i = 0; i < elem.length; i++) {
            if (tofind == elem[i]) {
                return true;
            }
        }
        return false;
    }
//查找当前元素的下标
    @Override
    public int indexOf(int tofind) {
        for (int i = 0; i < elem.length; i++) {
            if (tofind == elem[i]) {
                return i;
            }
        }
            return -1;

    }
//获取pos的位置
    @Override
    public int get(int pos) {
        //1.pos是否合法
        checkPosOfAdd( pos);
        //2.pos是否为空
        if(isEmpty()) {
            throw new IEmptyException("顺序表为空");
        }
        return elem[pos];
    }
    private void checkPosGet(int pos) {
        if(pos < 0 || pos >= this.useSize) {
            throw new PosException("pos位置不合法");
        }
    }
  public boolean isEmpty() {
     return useSize == 0;
    }

    @Override
    public void set(int pos,int value) {
    //1.判断pos是否合法
        checkPosGet(pos);
        if(isEmpty()){
           throw new PosException("位置不合法"+pos);
        }
        elem[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        if(isEmpty()) {
          throw new IEmptyException("顺序表为空，不能删除！");
        }
        int index = indexOf(toRemove);
        for (int i = index; i < useSize-1; i++) {
            elem[i] = elem[i+1];
        }
        useSize--;
    }

    @Override
    public void clear() {
        useSize = 0;
    }

    private void checkPosOfAdd(int pos) {
        if(pos < 0 || pos > useSize) {
             throw new PosException("pos位置为"+pos);
        }
    }
}
